<?php
	session_start();
	if(!$_SESSION["username"]){
		//not logged in
		header("location:login.php");
		}

	// Connect to server and select databse.
	mysql_connect("localhost", "root", "")or die("cannot connect"); 
	mysql_select_db("Project 5.5")or die("cannot select DB");
	
	$groupid= $_GET['groupid'];
	
	$sql="SELECT User_ID FROM users WHERE Username='".$_SESSION["username"]."'";
	$result=mysql_fetch_row(mysql_query($sql));
	$userid=$result[0];
	
	$sql="SELECT Group_Members FROM groups where Group_ID='".$groupid."'";
	$result=mysql_fetch_row(mysql_query($sql));
	
	//removes student from group members string
	
	$members=explode(',',$result[0]);
		
	$memberstring='';
	for($i=0;$i<sizeof($members);$i++){
	echo $members[$i]."<br>";
		if($members[$i]==$userid){
			unset($members[$i]);
		}else{
			$memberstring=$memberstring.$members[$i].',';
		}
	}
	$memberstring = rtrim($memberstring, ',');
	
	//deletes group if empty
	
	if(!$memberstring==''){
		$sql="UPDATE groups SET Group_Members='".$memberstring."' WHERE Group_ID=".$groupid;
	}else{
		$sql="DELETE FROM groups WHERE Group_ID=".$groupid;
	}
	$result=mysql_query($sql);
	
	$sql="UPDATE studentinfo SET Group_ID=0 WHERE User_ID=".$userid;
	$result=mysql_query($sql);
	
	header("location:groups.php");
	
	
?>
